import axios from "axios";
import { MessageBox, Message } from "element-ui";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { getData ,errData} from "@/utils/tracking"

const service = axios.create({
	baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
	withCredentials: true, // send cookies when cross-domain requests
	timeout: 10000000, // request timeout
});
let begin = "" // 请求开始时间

service.interceptors.request.use(
	(config) => {
		const hasToken = getToken();
		if (hasToken) {
			config.headers["X-Token"] = getToken();
			config.headers["Authorization"] = getToken();
		}
		begin=new Date().getTime()
		return config;
	},
	(error) => {
		return Promise.reject(error);
	}
);

service.interceptors.response.use(
	(response) => {
		const res = response.data;
		let token = response.headers["authorization"];
		getData(response,begin)
		if (token) {
			setToken(token);
		}

		if (res.errcode !== 0) {
			// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
			if (
				res.errcode === 508 ||
				res.errcode === 512 ||
				res.errcode === 514 ||
				res.errcode === 401
			) {
				// to re-login
				MessageBox.confirm("请重新登录？", "提示", {
					confirmButtonText: "确定",
					type: "error",
				})
					.then(() => {
						removeToken();
						location.reload();
					})
					.catch(() => {
						removeToken();
						location.reload();
					});
				return;
			}
		}
		if (
			res.errcode === 40001 ||
			res.errcode === 40002 ||
			res.errcode === 40003
		) {
			let url = res.errmsg;
			window.location.href = url;
		}
		return res;
	},
	(error) => {
		errData(error,begin)
		// Message.error("请重新登录");
		// setTimeout(()=>{
		//   store.dispatch('user/resetToken').then(() => {
		//     location.reload()
		//   })
		// },500)

		// console.log(error) // for debug
		// Message({
		//   message: error.message,
		//   type: 'error',
		//   duration: 5 * 1000
		// })

		return Promise.reject(error);
	}
);

export default service;
